'use strict';

const Controller = require('egg').Controller;
const CryptoJS = require("crypto-js");

class HomeController extends Controller {
  constructor(ctx) {
    super(ctx);
  }

  async index(ctx) {
    let path = ctx.path.toLowerCase();

    if (path.startsWith('/login')) {
      ctx.clearToken();
      return await ctx.renderClient('login.js', { ctx });
    }

    let token = ctx.cookies.get("token", { httpOnly: false, signed: false });
    let userInfo = [];
    if (token) {
      token = CryptoJS.AES.decrypt(token, ctx.app.config.keys, { iv: 0, mode: CryptoJS.mode.CBC }).toString(CryptoJS.enc.Utf8);
      userInfo = token.split("||");

      if (this.isInvalid(userInfo)) {
        return ctx.redirect("/login");
      }

      let isAdmin = this.isAdmin(token, userInfo)
      if (!path.startsWith('/admin') && isAdmin) {
        return ctx.redirect("/admin");
      }

      if (path.startsWith('/admin') && isAdmin) {
        return await ctx.renderClient('back.js', { ctx });
      }
    }

    if (path.startsWith("/admin") && !token) {
      return ctx.redirect("/login");
    }

    return await ctx.renderClient('front.js', { ctx });

  }

  isAdmin(token, userInfo) {
    return token && userInfo.length == 5 &&
      Number(userInfo[4]) > new Date().getTime() &&
      (userInfo[3] === "employee" || userInfo[3] === "admin")
  }

  isInvalid(userInfo) {
    return userInfo.length != 5 ||
      Number(userInfo[4]) < new Date().getTime()
  }
};

module.exports = HomeController;
